package com.csdj.job;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 处理类
 */
public class Paraser {

    /**
     * 读取模板
     * @param path  模板的路径
     * @return  模板内容
     */
    public String readTemplate(String path){
        StringBuilder sb = new StringBuilder();
        FileReader reader = null;
        try {
            reader = new FileReader(path);
            char[] buf = new char[256];
            while((reader.read(buf)) != -1){
                sb.append(buf);
            }
            return sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public String readTemp(String path){
        StringBuilder sb = new StringBuilder();
        try(FileReader reader = new FileReader(path)){
            char[] buf = new char[256];
            while((reader.read(buf)) != -1){
                sb.append(buf);
            }
            return sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存数据
     * @param result  结果
     * @param path    保存文件的路径
     */
    public void writeResult(String result,String path) throws IOException {
        FileWriter writer = new FileWriter(path);
        writer.write(result);
        writer.close();
    }


    /**
     * 数据替换
     * @param template 模板
     * @param cat  数据
     * @return
     */
    public String replaceParse(String template,Cat cat){
        //入参校验
        if(cat == null)return template;
        if(template == null)return "";

        String res = template.replace("{name}",cat.getName());
        res = res.replace("{type}",cat.getType());
        res = res.replace("{master}",cat.getMaster());
        return res;
    }
}
